<template>


          <div class="calendar-box" ref="box">

            <div class="info-title">企业诉求日历</div>

            <img src="../../assets/bj-1.png" alt="" class="bj-1">
            <img src="../../assets/bj-2.png" alt="" class="bj-2">
            <img src="../../assets/bj-3.png" alt="" class="bj-3">
            <img src="../../assets/bj-4.png" alt="" class="bj-4">
            <div class="calendar-wrapper" ref="box1">
              <div class="calendar-toolbar">
                <div class="prev" @click="prevMonth">上个月</div>
                <div class="current">{{ currentDateStr }}</div>
                <div class="next" @click="nextMonth">下个月</div>
                <div class="today" @click="today">今天</div>

              </div>


              <div class="calendar-week">
                <div
                  class="week-item calendarBorder"
                  v-for="item of weekList"
                  :key="item"
                >
                  {{ item }}
                </div>
              </div>
              <div class="calendar-inner">
                <div
                    class="calendar-item calendarBorder"
                    v-for="(item, index) of newcanderList"
                    :key="index"
                    :class="{
                      'calendar-item': true,
                      calendarBorder: true,
                      'a':item.colorin,
                      'calendar-item-hover': !item.disable,
                      'calendar-item-disabled': item.disable,
                      'calendar-item-checked':
                        dayChecked && dayChecked.value == item.value,
                    }"
                    @click.stop="handleClickDay(item)"
                  >

                  {{ item.date }}
                </div>
              </div>
               <div class="dialog" v-if="hovercheck" :style="{left:0, top: y+'px'}">

                    <div class="diahead">
                        <div class="headleft">{{timetil}}</div>
                        <div @click="hovercheck =false" class="headright">X</div>
                    </div>
                    <div class="newlist">
                        <ul>
                          <li v-for="(item,index) in newList" :key="index">{{index+1}}.{{item.articleTitle}}</li>
                        </ul>
                    </div>
               </div>
            </div>
          </div>


</template>

<script>
import user from "../../plugins/user"

export default {
  emits:['selectChange'],
  data() {
    return {
      newopen:false,
      showYearMonth: {}, // 显示的年月
      calendarList: [], // 用于遍历显示
      shareDate: new Date(), // 享元模式，用来做 日期数据转换 优化
      dayChecked: {}, // 当前选择的天
      weekList: ["一", "二", "三", "四", "五", "六", "日"], // 周
      list:[],
      x:0,
      y:12.5,
      hovercheck:false,
      timetil:null,
      newList:[],
      cesList:[],
      newcanderList:[],
    };
  },
  mounted(){

    // this.mouseFllow();

  },
  created() {
    this.initDataFun(); // 初始化数据
  },
  computed: {
    // 显示当前时间
    currentDateStr() {
      let { year, month } = this.showYearMonth;
      return `${year}年${this.pad(month + 1)}月`;
    },
    datalist(){
      var list = this.list
      return list
    }
  },
  methods: {
    // calendarPupop(){
    //   this.hovercheck = true

    // },

    async getworkData(params){
          await user.getworkDynamics(params).then((res) => {
                  this.list =  res.data;


          })
    },

    //#region 计算日历数据
    // 初始化数据
    getnian(){
      let { year} = this.showYearMonth;
      let time = `${year}`;
      return time
    },
     getyue(){
      let { month} = this.showYearMonth;
      // let nian = `${year}`
      let time = `${month+1}`;
      return this.pad(time)
    },
    async initDataFun() {
      this.newcanderList = [];
      // 初始化当前时间
      this.setCurrentYearMonth(); // 设置日历显示的日期（年-月）
      this.createCalendar(); // 创建当前月对应日历的日期数据
      this.getCurrentDay(); // 获取今天
      let time =  this.getnian();
      let yue =  this.getyue();
      let params = {
          nian:time,
          yue:yue
      }

      // this.getworkData(params);
      await user.getworkDynamics(params).then((res) => {
          this.list =  res.data;

      })

      for (let j = 0; j < this.calendarList.length; j++) {

         let a = false
         for (let i = 0; i < this.list.length; i++) {
             if(this.calendarList[j].value == this.list[i].cTime){
              a =true
                 break;
             }
         }
         this.newcanderList.push({
                     value:this.calendarList[j].value,
                     date:this.calendarList[j].date,
                     month:this.calendarList[j].month,
                     year:this.calendarList[j].year,
                     colorin:a,
                     disable:this.calendarList[j].disable,

                 })

      }
    },
    // 设置日历显示的日期（年-月）
    setCurrentYearMonth(d = new Date()) {
      let year = d.getFullYear();
      let month = d.getMonth();
      let date = d.getDate();
      this.showYearMonth = {
        year,
        month,
        date,
      };
    },
    getCurrentDay(d = new Date()) {
      let year = d.getFullYear();
      let month = d.getMonth();
      let date = d.getDate();
      this.dayChecked = {
        year,
        month,
        date,
        value: this.stringify(year, month, date),
        disable: false
      };
    },
    // 创建当前月对应日历的日期数据
    async createCalendar() {
      // 一天有多少毫秒
      const oneDayMS = 24 * 60 * 60 * 1000;
      let list = [];
      let { year, month } = this.showYearMonth;

      // #region
      // ---------------仅仅只算某月的天---------------
      //   // 当前月，第一天和最后一天的毫秒数
      //   let begin = new Date(year, month, 1).getTime();
      //   let end = new Date(year, month + 1, 0).getTime();

      // ---------------计算某月前后需要填补的天---------------
      // 当前月份第一天是星期几, 0-6
      let firstDay = this.getFirstDayByMonths(year, month);
      // 填充多少天，因为我将星期日放到最后了，所以需要另外调整下
      let prefixDaysLen = firstDay === 0 ? 6 : firstDay - 1;
      // 向前移动之后的毫秒数
      let begin = new Date(year, month, 1).getTime() - oneDayMS * prefixDaysLen;
      // 当前月份最后一天是星期几, 0-6
      let lastDay = this.getLastDayByMonth(year, month);
      // 填充多少天，因为我将星期日放到最后了，所以需要另外调整下
      let suffixDaysLen = lastDay === 0 ? 0 : 7 - lastDay;
      // 向后移动之后的毫秒数
      let end = new Date(year, month + 1, 0).getTime() + oneDayMS * suffixDaysLen;
      // // 计算左侧时间段的循环数
      // let rowNum = Math.ceil((end - begin) / oneDayMS / 7);
      // let newPeriod = [];
      // for (let i = 0; i < rowNum; i++) {
      //   newPeriod.push({});
      // }
      // #endregion

      // 填充天

      while (begin <= end) {
        // 享元模式，避免重复 new Date
        this.shareDate.setTime(begin);
        let year = this.shareDate.getFullYear();
        let curMonth = this.shareDate.getMonth();
        let date = this.shareDate.getDate();
        list.push({
          year: year,
          month: curMonth + 1, // 月是从0开始的
          date: date,
          value: this.stringify(year, curMonth, date),
          disable: curMonth !== month,
        });
        this.cesList.push(this.stringify(year, curMonth, date))
        begin += oneDayMS;
      }

      this.calendarList = list;
    },
    // 格式化时间
    stringify(year, month, date) {
      let str = [year, this.pad(month + 1), this.pad(date)].join("-");
      return str;
    },
    // 对小于 10 的数字，前面补 0
    pad(str) {
      return str < 10 ? `0${str}` : str;
    },
    // 点击上一月
    async prevMonth() {
      this.showYearMonth.month--;
      this.recalculateYearMonth(); // 因为 month的变化 会超出 0-11 的范围， 所以需要重新计算
      this.createCalendar(); // 创建当前月对应日历的日期数据
      let time = this.getnian();
      let yue =  this.getyue();
      let params = {
          nian:time,
          yue:yue
      }
      // this.getworkData(params);
      await user.getworkDynamics(params).then((res) => {
          this.list =  res.data;
      })
      this.newcanderList = [];
      for (let j = 0; j < this.calendarList.length; j++) {

         let a = false
         for (let i = 0; i < this.list.length; i++) {
             if(this.calendarList[j].value == this.list[i].cTime){
              a =true
                 break;
             }
         }
         this.newcanderList.push({
                     value:this.calendarList[j].value,
                     date:this.calendarList[j].date,
                     month:this.calendarList[j].month,
                     year:this.calendarList[j].year,
                     colorin:a,
                     disable:this.calendarList[j].disable,

                 })

      }
    },
    today(){
        this.initDataFun();
    },
    // 点击下一月
    async nextMonth() {
      this.showYearMonth.month++;
      this.recalculateYearMonth(); // 因为 month的变化 会超出 0-11 的范围， 所以需要重新计算
      this.createCalendar(); // 创建当前月对应日历的日期数据
      let time = this.getnian();
      let yue =  this.getyue();
      let params = {
          nian:time,
          yue:yue
      }
      await user.getworkDynamics(params).then((res) => {
          this.list =  res.data;
      })
      this.newcanderList = [];
      for (let j = 0; j < this.calendarList.length; j++) {

         let a = false
         for (let i = 0; i < this.list.length; i++) {
             if(this.calendarList[j].value == this.list[i].cTime){
              a =true
                 break;
             }
         }
         this.newcanderList.push({
                     value:this.calendarList[j].value,
                     date:this.calendarList[j].date,
                     month:this.calendarList[j].month,
                     year:this.calendarList[j].year,
                     colorin:a,
                     disable:this.calendarList[j].disable,

                 })

      }
    },
    // 重算：显示的某年某月
    recalculateYearMonth() {
      let { year, month, date } = this.showYearMonth;

      let maxDate = this.getDaysByMonth(year, month);
      // 预防其他月跳转到2月，2月最多只有29天，没有30-31
      date = Math.min(maxDate, date);

      let instance = new Date(year, month, date);
      this.setCurrentYearMonth(instance);
    },
    // 判断当前月有多少天
    getDaysByMonth(year, month) {
      return new Date(year, month + 1, 0).getDate();
    },
    // 当前月的第一天是星期几
    getFirstDayByMonths(year, month) {
      return new Date(year, month, 1).getDay();
    },
    // 当前月的最后一天是星期几
    getLastDayByMonth(year, month) {
      return new Date(year, month + 1, 0).getDay();
    },
    // #endregion 计算日历数据

    // 操作：点击了某天
    handleClickDay(item) {
      if (!item || item.disable) return;
      if(this.datalist.length>0){
          this.datalist.forEach(i=>{
            if(i.cTime==item.value){
                this.hovercheck =true;
                this.timetil = i.cTime
                let a= this.$refs.box.offsetHeight-this.$refs.box1.offsetHeight
                this.y = this.$refs.box.offsetHeight - (a /2);
                this.newList = i.list;
            }
          })
      }else {
        // 跳转新闻列表
        // open("/gongyezhenxing-console/#/news/articles?startTime="+item.value)
        this.$emit('selectChange',item)
      }
    },

  },
};
</script>

<style lang="scss" scoped>

.calendar-box {
  width: 100%;
  height: 100%;
  display: flex;
  background-color: rgba(0, 24, 106, 0.5);
  border: 1px solid #20558b;
  justify-content: center;
  border-radius: 10px;
  align-items: center;

  .info-title{
    width: 158px;
    height: 43px;
    background: url('../../assets/info-title.png') no-repeat;
    position: absolute;
    top: -22px;
    left:50%;
    margin-left: -74px;
    color:#fff;
    font-size: 14px;
    font-weight: 600;
    line-height: 43px;
    text-align: center;
}
   .bj-1{
         position: absolute;
         left:-1px;
         top:-1px;
     }
     .bj-2{
         position: absolute;
         right:-1px;
         top:-1px;
     }
     .bj-3{
         position: absolute;
         right:-1px;
         bottom:-1px;
     }
     .bj-4{
         position: absolute;
         left:-1px;
         bottom:-1px;
     }
  .calendar-wrapper {
    // width: 100%;
    // height: 100%;
    // margin-top: 7%;
    // width: 95%;
    // height: 88%;
    // background-color: red;
    .calendar-toolbar {
      width: 100%;
      height: 30px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      color: #eee;
      .prev,
      .next,
      .today,
      .current {
        cursor: pointer;
        &:hover {
          color: #438bef;
        }
      }
    }
    .calendar-week {
      width: 100%;
    //   border-left: 1px solid #eee;
      display: flex;
      flex-wrap: wrap;
      .week-item {
        width: calc(100% / 7.3);

        height: calc(100% / 7.3);
        color: #d0c5c5;
        // border-top: 1px solid #eee;
      }
    }
    .calendar-inner {
      width: 100%;
    //   border-left: 1px solid #eee;
      // height: 80%;
      display: flex;
      flex-wrap: wrap;
      .calendar-item {
        width: calc(100% / 7.3);
        height: calc(100% / 7.3);
        color: #eee;
        border-radius: 8px;
        margin-top: .3vh;

      }
      .calendar-item-hover {
        cursor: pointer;
        &:hover {
          color: #121010;
          background-color: #438bef;
        }
      }
      .calendar-item-disabled {
        color: #9e9898;
        cursor: not-allowed;
      }
      .a{
        color: white;
        background: #5590e2;
      }
      .calendar-item-checked {
        color: #121010;

        background-color: #0089FF;
      }
    }
    .dialog{
            width: 14vw;
            height: 13.5vw;
            // border: solid 1px red;
            position: absolute;
            z-index: 999999;
            background-color: rgba(0, 24, 106, 0.5);
            border: 1px solid #20558b;

            left: 10px;
            top: 10px;
            .diahead{
              display: flex;
              justify-content: space-between;
              width: 100%;
              height: 20px;
              margin-top: 10px;
              .headleft{
                  margin-left: 5px;
                  color: white;
                  font-size: 16px;

              }
              .headright{
                margin-right: 14px;
                width: 30px;
                height: 100%;
                color: white;
                text-align: center;
              }
            }
            .newlist{
              height: calc(13.5vw - 20px);
              width: 100%;
                padding: 10px;
                box-sizing: border-box;

              ul{
                width: 100%;
                height: 100%;
                overflow-y: auto;
                li{
                  color: white;
                  margin-top: 2px;

                }

              }
                ul::-webkit-scrollbar{
                height: 8px;
              }
              ul::-webkit-scrollbar-thumb {
                    border-radius: 10px;
                    -webkit-box-shadow: inset 0 0 5px #0089FF;
                    background: #0089FF;
                }
              ul::-webkit-scrollbar-track {

              -webkit-box-shadow: inset 0 0 5px rgba(72, 45, 221, 0.2);
              border-radius: 10px;
              background: rgba(32, 6, 177, 0.2);
              /* border: none;
              background: none; */
                }
            }
            // display:none;
          }
    .calendarBorder {
      display: flex;
      justify-content: center;
      align-items: center;
    //   border-bottom: 1px solid #eee;
    //   border-right: 1px solid #eee;
    }
  }
}
</style>
